package com.shujia.flink.table

import org.apache.flink.streaming.api.scala._
import org.apache.flink.table.api._
import org.apache.flink.table.api.bridge.scala._
import org.apache.flink.types.Row

object Demo1TableEnv {
  def main(args: Array[String]): Unit = {

    //创建flink 环境
    val bsEnv: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    //设置table 环境的一些参数
    val bsSettings: EnvironmentSettings = EnvironmentSettings.newInstance()
      .useBlinkPlanner() //使用blikc计划器
      .inStreamingMode() //流模式
      .build()

    // 创建flink  table 环境
    val bsTableEnv: StreamTableEnvironment = StreamTableEnvironment.create(bsEnv, bsSettings)


    /**
      * 读取数据 -- 创建source表
      *
      */


    bsTableEnv.executeSql(
      """
        |CREATE TABLE student (
        | id STRING,
        | name STRING,
        | age BIGINT,
        | gender STRING,
        | clazz STRING
        |) WITH (
        | 'connector' = 'kafka',
        | 'topic' = 'student4',
        | 'properties.bootstrap.servers' = 'master:9092,node1:9092,node2:9092',
        | 'properties.group.id' = 'testGroup',
        | 'format' = 'csv',
        | 'csv.field-delimiter' = ',' ,
        | 'scan.startup.mode' = 'earliest-offset'
        |)
      """.stripMargin)

    /**
      * 编写sql处理数据
      * 实时统计班级的人数
      *
      * sqlQuery: 执行查询语句，返回一个流表的对象
      */

    /* val countTable: Table = bsTableEnv.sqlQuery(
       """
         |select clazz,count(1) from student group by clazz
         |
       """.stripMargin)


     //将表转换成流   打印出来
     val countDS: DataStream[(Boolean, Row)] = countTable.toRetractStream[Row]
     //打印结果
     countDS.print()
     bsEnv.execute()*/


    /**
      * 创建sink 表
      *
      */

    bsTableEnv.executeSql(
      """
        |CREATE TABLE print_table (
        | clazz STRING,
        | num BIGINT
        |) WITH (
        | 'connector' = 'print'
        |)
        |
      """.stripMargin)

    /**
      *
      * 将数据写如mysql的 sink 表
      * 需要先在mysql中创建表
      */

    bsTableEnv.executeSql(
      """
        |
        |CREATE TABLE mysql_sink (
        |  clazz STRING,
        |  num BIGINT,
        |  PRIMARY KEY (clazz) NOT ENFORCED
        |) WITH (
        |   'connector' = 'jdbc',
        |   'url' = 'jdbc:mysql://master:3306/bigdata?useUnicode=true&characterEncoding=utf-8',
        |   'table-name' = 'clazz_num',
        |   'username' = 'root',
        |   'password' = '123456'
        |)
        |
      """.stripMargin)

    /**
      * 处理数据，将结果写入sink表
      *
      */

    bsTableEnv.executeSql(
      """
        |insert into mysql_sink
        |select clazz,count(1) as num from student group by clazz
        |
      """.stripMargin)


  }

}
